package tbdp.tool.spi;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

import tbdp.tool.common.JobConstants;
import tbdp.tool.config.WriterConfig;
import tbdp.tool.context.JobContext;
import tbdp.tool.util.VariableContext;
import tbdp.tool.util.VariableUtils;

/**
 * @author xbkaishui
 * @version $Id: Writer.java, v 0.1 2017-06-17 下午3:05 xbkaishui Exp $$
 */
public abstract class Writer {

    protected Logger logger = LoggerFactory.getLogger(Writer.class);

    /**
     * 根据任务配置写入数据
     */
    public abstract void write(JobContext context, RecordIterator recordIterator);


    /**
     * 写入完成 ， 数据同步，文件目录转移等
     */
    public void postWriter(JobContext context, RecordIterator recordIterator) {

    }

    /**
     * 关闭写出
     */
    public abstract void close(JobContext context);

    public abstract String getType();

    /**
     * 获取writer 写出的文件路径
     */
    protected String getFilePath(JobContext context) {
        String filePath = (String) context.getValue(JobConstants.DATA_FILE_PATH);
        if (StringUtils.isEmpty(filePath)) {
            WriterConfig writerConfig = context.getJobConfig().getWriter();
            Map<String, Object> config = writerConfig.getConfig();
            String filePattern = (String) config.get(JobConstants.FILE_PATH_PATTERN);
            filePath = VariableUtils.substituteVars(filePattern, VariableContext.instance().getCtx());
            context.put(JobConstants.DATA_FILE_PATH, filePath);
        }
        return filePath;
    }

    /**
     * 获取临时文件存储位置
     */
    protected String getTmpFilePath(JobContext context) {
        String tmpFilePath = context.getValueAsString(JobConstants.TEMP_FILE_PATH);
        if (StringUtils.isEmpty(tmpFilePath)) {
            WriterConfig writerConfig = context.getJobConfig().getWriter();
            String tmpDir = writerConfig.getTmpFileDir();
            if (StringUtils.isEmpty(tmpDir)) {
                tmpDir = System.getProperty("java.io.tmpdir") + "/data_export_tmp/";
            }
            logger.warn("tmpdir: " + tmpDir);
            tmpFilePath = tmpDir + "/" + System.currentTimeMillis();
            context.put(JobConstants.TEMP_FILE_PATH, tmpFilePath);
        }
        return tmpFilePath;
    }


}
